package com.cskaoyan.order.service.impl;

import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.service.OrderPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author：HeXiangZhi
 * @data: 2022/12/7 16:02
 * @Description: TODO
 */
@Slf4j
@Service
public class OrderPayServiceImpl implements OrderPayService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;

    /**
     *  支付成功时，更新订单状态，更新锁定库存，更新订单商品库存状态
     * @return
     */
    @Override
    public void payOrderSuccess(String orderId) {
        // 1、更新订单表 （状态+支付时间+更新时间）
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(1);
        order.setUpdateTime(new Date());
        order.setPaymentTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);

        // 2、更新库存表（锁定库存减少）
        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId",orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        for (OrderItem orderItem : orderItems) {
            Stock stock = new Stock();
            stock.setItemId(orderItem.getItemId());
            stock.setStockCount(0L);
            stock.setLockCount(-orderItem.getNum());
            stockMapper.updateStock(stock);
        }

        // 3、更新订单-商品表（状态+更新时间）
        orderItemMapper.updateStockStatus(3,orderId);

    }
}
